/**
 *  使用优惠劵
 */
define(function(require,exports,module) {
    var myPub = require('../mod/public');

    var oShadow = $('.js_shadow');				        //阴影
    var oCouponSeletSide = $('.js_couponSeletSide');    //优惠劵领取弹框
    var oUseCoupon = $('.js_useCoupon');                //优惠劵列表展示按钮-商品详情页面
    var oGoodsCoupon = $('.js_goodsCoupon');            //详情优惠劵框
    var oMoreBtnBox = $('.js_moreBtnBox');              // 显示没有了 或者加载中的按钮
    var oCoupSwiper = $('.js_coupSwiper');              // swiper区域的高度
    var oCouponList = $('.js_couponList');              // 优惠券列表的高度
    var timer = null;
    var bTapOff = true;                                 // 点击领取优惠券时防止重复点击
    var tap_timer = null;                               // 防止重复点击定时器
    var oSpellListPopup = $('.js_spellListPopup');      // 更多列表的弹窗
    var oSpellListArea = $('.js_spellListArea');        // 拼团
    var oSpellPopupList = $('.js_spellPopupList');      // 弹窗拼单列表
    var oPoupCloseBtn = $('.js_iconCloseBtn');          // 关闭拼单弹窗按钮
    var spellListUrl = '/m/o/activity/tuangou/1.0/joinedList';      // 未拼单完成订单接口

    var moveHeight = oCouponSeletSide.outerHeight(true);    //物品详情优惠劵高度
    oCouponSeletSide.css({'bottom': -moveHeight });


    var oCloseBtn = $('.js_closeBtn');
    var bSideOff = true;
    var loadAll = false;  //判断是否成功请求过优惠券

    // var oGetNow = $('.js_getNow');   //立即领取
    var NavName = ['店铺券','平台券'];
    // 物品详情优惠劵领取
    oUseCoupon.on('click', function () {
        if(!bSideOff)  return;
        bSideOff = false;

        oCouponSeletSide.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
            if(couponArea.bSwiperLoadOff[couponArea.busTuangouDetailNum]){                 // 已经点过 再点击就不加载数据了
                couponArea.bSwiperLoadOff[couponArea.busTuangouDetailNum] = false;         // 已经点过 再点击就不加载数据了
                couponArea.getDeatilData(couponArea.busTuangouDetailNum);                  // 加载数据
                couponArea.oswiperSlidMain.slideTo(couponArea.busTuangouDetailNum, 100);   // 滑动到缓存页面
            }
        });

        clearTimeout(timer);
        timer = setTimeout(function () {
            bSideOff = true
        },250);


        myPub.HamstopPropaga();
    });

    // 阴影点击关闭
    oShadow.on('click', function () {
        //隐藏服务
        oCouponSeletSide.stop().animate({bottom:-moveHeight},300,function(){
            oCouponSeletSide.hide();
            oShadow.hide();
        });
        myPub.HamstopPropaga();
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

    });

    oCloseBtn.on('click', function () {
        //隐藏服务
        oCouponSeletSide.stop().animate({bottom:-moveHeight},300,function(){
            oCouponSeletSide.hide();
            oShadow.hide();
        });

        myPub.HamstopPropaga();
    });

    //立即领取
    function getNow() {
        // 立即领取操作
        $('.js_getNow').off('click');
        $('.js_getNow').on('click', function (e) {
            if(bTapOff){
                bTapOff = false;
                e.stopPropagation();
                var _tarTag = e.target;
                var target;
                target = $(_tarTag);
                if(_tarTag.nodeName.toLowerCase() == 'button') {
                    var couponId = e.currentTarget.dataset.couponid;
                    // alert(couponId);
                    G_JSON_GET('/coupon/drawSupplierCoupon',{couponId: couponId},function (data) {
                        if(data.status == 'success'){
                            myPub.TipLayer(data.message);
                            target.hide().next().show();
                            if(typeof mui !== 'undefined'){
                                myPub.OffMuiEvent(true);
                            }
                        }else {
                            myPub.TipLayer(data.message);
                        }
                    })

                }

                myPub.HamstopPropaga();
            }
        });
        clearTimeout(tap_timer);
        tap_timer = setTimeout(function () {
            bTapOff = true;
        },250)
    }



    var couponArea = {
        paggerr:[1,1],                       // 页码数
        startNum:[0,0],                      // 开始加载时的数据
        limit:5,                            // 每次请求的数据
        bSwiperLoadOff:[true,true],          // 切换页面是否加载数据
        bLoadOff:[true,true],                // 滚动是否加载数据
        busTuangouDetailNum:0,                      // 当前优惠券下标
        oswiperSlidMain:null,                // swiper主体
        time_Scroll:null,                    // 滚动加载定时器
        // 获取优惠券数据
        getDeatilData:function (index) {
            var _this = this;
            G_JSON_POST('/coupon/getGoodsDetailCoupons',{
                supplierId: supplierId,
                id: goodsId,
                goodsCategoryId: goodsCategoryId,
                type:index,
                pageNo:_this.paggerr[index]
            },function (data) {
                // console.log('couponData---店铺',index,data);
                if(data.status == 'success'){
                    var getData = data.supplierCoupons;     // 优惠券列表
                    if(getData && getData.length > 0){
                        // 我假设优惠券的面额为10的是平台券即couponNum == 10为平台券
                        if(getData != null && getData.length > 0){
                            oCouponList.eq(index).append(couponArea.couponHtml(getData));
                            _this.startNum[index] = _this.limit*_this.paggerr[index];
                            _this.paggerr[index]++;
                            oMoreBtnBox.eq(index).find('.js_loading').show();
                            // 当数据小于每次请求的数据时
                            if(getData.length < _this.limit){
                                // _this.bLoadOff[index] = false;
                                oMoreBtnBox.eq(index).find('.js_loadNull').hide();
                                oMoreBtnBox.eq(index).find('.js_loading').hide();
                            }

                            if(oCoupSwiper.height() > oCouponList.eq(index).height()){
                                // 如果容器的高度小于轮播区域的高度就要再加载一次
                                _this.startNum[index] = _this.limit*_this.paggerr[index];
                                _this.paggerr[index]++;
                                _this.getDeatilData(index);
                            }

                        }
                    }
                    // 数据是0 但不是第一页时
                    else if(getData == 0 && _this.paggerr[index] > 1){
                        _this.bLoadOff[index]  = false;
                        //把加载中隐藏，显示没有更多
                        oMoreBtnBox.eq(index).find('.js_loading').hide();
                        oMoreBtnBox.eq(index).find('.js_loadNull').show();
                        // return
                    }
                    // 数据是0  又是第一页时
                    else if(getData == 0 && _this.paggerr[index] < 2){
                        _this.bLoadOff[index]  = false;
                        _this.busTuangouDetailNum = 1;
                        _this.bSwiperLoadOff[0] = false;
                        oCouponList.eq(index).append(couponArea.nullCoupon());
                        // myPub.TipLayer('没有优惠券！');
                        oMoreBtnBox.eq(index).find('.js_loading').hide();
                        // return
                    }
                    else{
                        _this.bLoadOff[index]  = false;
                        _this.busTuangouDetailNum = 1;
                        _this.bSwiperLoadOff[0] = false;
                        oCouponList.eq(index).append(couponArea.nullCoupon());
                        // myPub.TipLayer('没有优惠券！');
                        oMoreBtnBox.eq(index).find('.js_loading').hide();
                        // return
                    }
                    getNow();   //启动立即领取可点
                    /*oCouponSeletSide.show().stop().animate({ 'bottom':0 },300,function() {
                        oShadow.show();
                        // bSideOff = true
                    });*/
                }else {
                    // bSideOff = true;
                    $('.js_couponList').eq(index).append(couponArea.nullCoupon());
                    myPub.TipLayer(data.msg);
                }
            });
        },

        // 滚动加载
        scrollAddData:function (index) {
            var _this = this;
            var minScrHeight = 50;
            var oCouponIntor = $('.js_couponIntor').eq(index);
            var oScroll = $('.js_scroll');
            oScroll.on('scroll',function () {
                var afterScroll = $(this).scrollTop();
                // 滚动距离页面底部200像素，延迟250毫秒加载
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function () {
                    if((oCouponIntor[0].scrollHeight - afterScroll - oScroll.height()) < minScrHeight){
                        if(_this.bLoadOff[_this.busTuangouDetailNum]){
                            // 滚动底部页数增加 起始数据等于上次结束数据  新的结束等于页数*页码数
                            _this.startNum[_this.busTuangouDetailNum] = _this.limit*_this.paggerr[_this.busTuangouDetailNum];
                            _this.paggerr[_this.busTuangouDetailNum]++;
                            _this.getDeatilData(_this.busTuangouDetailNum);
                        }
                    }
                },250)
            })
        },

        // 优惠券弹框切换
        couponSlider:function (NavName) {
            var oCoupSwiper = $('.js_coupSwiper');
            var oCoupNavUl = $('.js_coupNavUl');
            var oCouponIntor = $('.js_couponIntor');
            var _this = this;
            _this.oswiperSlidMain = oCoupSwiper.swiper({
                pagination: oCoupNavUl[0],
                paginationClickable: true,
                observer: true,
                observeParents: true,
                onInit: function (swiper) {
                    var index = swiper.activeIndex;
                    // oCouponIntor.hide().eq(index).show().css({'height': 'auto'});
                },
                paginationBulletRender:function(swiper,index,className){
                    //添加导航
                    return '<li class="Bflex1 '+className+'" data-type="'+index+'">'+ NavName[index] +'</li>';
                },
                onSlideChangeEnd: function (swiper) {
                    var index = swiper.activeIndex;
                    // var getHeight = oCouponIntor.eq(index).outerHeight(true);

                    oCouponIntor.hide().eq(index).show().css({'height': 'auto'});
                    _this.busTuangouDetailNum = index;
                    if(_this.bSwiperLoadOff[index]){
                        _this.bSwiperLoadOff[index] = false;
                        _this.getDeatilData(index);
                    }
                    // oWrap.stop().animate({scrollTop: oSildeNavUl_Top}, 10);
                    /*myPub.JudgeAppHide(function () {
                        //ios
                        window.webkit.messageHandlers.AppModel.postMessage({body: getHeight});
                    });*/
                }
            })
        },

        // 没有优惠券时的拼接html
        nullCoupon:function () {
            var shtml = '<div class="nullCoupon">'+
                '   <div class="nullCouponImg">'+
                '       <img src="/static_v4/image/wonderful/coupon-null.png" alt="">'+
                '   </div>'+
                '   <div class="">'+
                '       <p>没有优惠券哦~</p>'+
                '   </div>'+
                '</div>';
            return shtml
        },

        // 拼接优惠券的Html
        couponHtml:function (data) {
            var shtml = '';
            var data = data;
            for(var i=0; i<data.length; i++){
                if(data[i].supplierId == 0){
                    shtml += '<div class="coupon platCoupon" >'
                }else{
                    shtml += '<div class="coupon">'
                }
                shtml += '            <div class="couponBox" >' +
                    '                <div class="couponInfo HBox">' +
                    '                    <div class="couponInfoLeft HBox BoxCenter">' +
                    '                        <div class="couponPrice">' +
                    '                            <em>￥</em>' +
                    '                            <span>'+data[i].costPrice+'</span>' +
                    '                            <p>满'+data[i].needPrice+'元可用</p>' +
                    '                        </div>' +
                    '                    </div>' +
                    '                    <!--中间-->' +
                    '                    <div class="couponInfoCenter Bflex1 height_100">' +
                    '                        <div class="couponUseType">' +
                    '                            <h5 class="singleLine" >'+data[i].couponName+'</h5>' +
                    '                            <div class="tip_use" >' +
                    '                            </div>' +
                    '                            <div class="tip_useLimt Bflex1">' +
                    '                                <p>'+myPub.FormatDateTime(new Date(data[i].beginDate.time),"minDay",".")+"-"+myPub.FormatDateTime(new Date(data[i].endDate.time),"minDay",".")+'</p>' +
                    '                            </div>' +
                    '                        </div>' +
                    '                    </div>' ;
                if(data[i].isHasCoupon == 1){
                    shtml += '       <div class="couponInfoRight HBox BoxCenter">' +
                        '                 <div class="useThisCoupon HBox BoxCenter" data-couponId="'+ data[i].id +'">' +
                        '                        已领取' +
                        '                  </div>' +
                        '             </div>' ;
                }else {
                    shtml += '        <div class="couponInfoRight HBox BoxCenter">' +
                        '                   <div class="useThisCoupon">' +
                        '                        <button class="useThisCouponBtn HBox BoxCenter js_getNow" data-couponId="'+ data[i].id +'">立即领取</button>' +
                        '                        <div class="useThisCouponBtn HBox BoxCenter" data-couponId="'+ data[i].id +'">已领取</div>' +
                        '                   </div>' +
                        '              </div>' ;
                }


                shtml += '       </div>' +
                    '           </div>' +
                    '           <div class="gapBox gapBox_right">' +
                    '                <span class="gap gap_top"></span>' +
                    '                <span class="gap_line"></span>' +
                    '                <span class="gap gap_bot"></span>' +
                    '            </div>' +
                    '        </div>';
            }

            return shtml;
        }
    };

    couponArea.couponSlider(NavName);
    couponArea.getDeatilData(0);
    couponArea.scrollAddData(couponArea.busTuangouDetailNum);

    // 未完成拼单订单列表
    var spellList = {
        start:0,                    // 开始数据
        spellNum:0,                 // 现在拼单的单数
        limit:10,                   // 加载的数量
        getData:[],                 // 储存数据

        spellListData:function () {
            var _this = this;
            G_JSON_POST(spellListUrl,{
                'activityId':activityId,
                'start':_this.start,
                'limit':_this.limit
            },function (data) {
                if(data.ret.code == '0'){
                    var dataItem = data.data;
                    _this.spellNum = dataItem.count;
                    _this.getData = dataItem.list;
                    if(_this.getData && _this.getData.length > 0){
                        oSpellListArea.show();
                        _this.spellData(_this.getData.slice(0,2),_this.spellNum);
                        _this.spellPopup(_this.getData);
                        _this.CutDataTime(_this.getData);
                    }else{
                        oSpellListArea.hide();
                        console.log(data.ret.message)
                    }
                }else{
                    oSpellListArea.hide();
                    console.log(data.ret.message)
                }
            });
        },

        // 页面拼团Html
        spellData:function(data,num){
            var _this = this;
            var thtml = '';
            var lotHtml = '';
            for(var i = 0;i < data.length;i++){
                var headImg = '';
                if(data[i].memberImagePath && data[i].memberImagePath.length > 0){
                    if(data[i].memberImagePath.indexOf('http') != -1){
                        headImg = '<img src="'+data[i].memberImagePath+'" alt="">'
                    }else{
                        headImg = '<img src="'+HTTP_IMAGE_URL+data[i].memberImagePath+'" alt="">'
                    }
                }else{
                    headImg = '<img src="'+BASE+'/static_v4/image/sfddj.png" alt="">'
                }
                lotHtml +=
                    '<li class="spellListDel HBox">'+
                    '   <div class="spellListHead">'+
                            headImg+
                    '   </div>'+
                    '   <div class="spellListPerson flexBox spBe BoxCenter Bflex1">'+
                    '       <div class="spellListName">'+data[i].userName+'</div>'+
                    '       <div class="spellListActive HBox BoxCenter">'+
                    '           <div class="spellActive">'+
                    '               <p class="spellListNum">还差<span>'+data[i].devCount+'</span>人拼成</p>'+
                    '               <p class="spellListTime">剩余'+
                    '                   <span class="js_timeDel"></span><i class="js_msTime"></i>'+
                    '               </p>'+
                    '           </div>'+
                    '           <div class="spellListGo">'+
                    '               <a href="'+BASE+'/GroupBuying/GroupBuyingDetail/'+data[i].recordId+'?'+goodsSn+'">'+
                    '                   <span>去拼单</span>'+
                    '               </a>'+
                    '           </div>'+
                    '       </div>'+
                    '   </div>'+
                    '</li>';
            }
            thtml =
                '<div class="spellListBg">'+
                '   <div class="spellListTit flexBox spBe">'+
                '       <div class="spellListCri">'+activeNum+'人团·'+num+'人在拼单，可直接参与</div>'+
                '       <div class="spellListMore js_spellListMore">查看更多<em class="iconStyle icon-href-right"></em></div>'+
                '   </div>'+
                '   <div class="spellListCon">'+
                '       <ul class="">'+
                            lotHtml+
                '       </ul>'+
                '   </div>'+
                '</div>';
            oSpellListArea.append(thtml);
        },

        // 弹窗拼团Html
        spellPopup:function(data){
            var _this = this;
            var thtml = '';
            for(var i = 0;i < data.length;i++){
                var headImg = '';
                if(data[i].memberImagePath && data[i].memberImagePath.length > 0){
                    if(data[i].memberImagePath.indexOf('http') != -1){
                        headImg = '<img src="'+data[i].memberImagePath+'" alt="">'
                    }else{
                        headImg = '<img src="'+HTTP_IMAGE_URL+data[i].memberImagePath+'" alt="">'
                    }
                }else{
                    headImg = '<img src="'+BASE+'/static_v4/image/sfddj.png" alt="">'
                }
                thtml +=
                    '<li class="HBox">'+
                    '   <div class="spellListPopupHead">'+
                            headImg+
                    '   </div>'+
                    '   <div class="spellListPopupList Bflex1 flexBox spBe BoxCenter">'+
                    '       <div class="spellListPopupDel">'+
                    '           <div class="HBox spellPopupArea">'+
                    '               <div class="spellPopupName">'+data[i].userName+'</div>'+
                    '               <div class="spellPopupNum">还差'+data[i].devCount+'人</div>'+
                    '           </div>'+
                    '           <div class="spellPopupTime">剩余'+
                    '               <span class="js_timeDel"></span><i class="js_msTime"></i>'+
                    '           </div>'+
                    '       </div>'+
                    '       <div class="spellPopupGo">'+
                    '           <a href="'+BASE+'/GroupBuying/GroupBuyingDetail/'+data[i].recordId+'?'+goodsSn+'">'+
                    '               <span>去拼单</span>'+
                    '           </a>'+
                    '       </div>'+
                    '   </div>'+
                    '</li>';
            }
            oSpellPopupList.html(thtml)
        },

        // 点击事件
        spellListEvent:function () {
            var _this = this;
            // 查看更多按钮
            oSpellListArea.on('click',function (e) {
                var target = e.target;
                if($(target).hasClass('js_spellListMore')){
                    oSpellListPopup.show();
                    // _this.spellListData(10);
                    oShadow.show();
                }
            });
            // 关闭按钮关闭拼单弹窗
            oShadow.on('click',function (e) {
                $(this).hide();
                oSpellListPopup.hide();
                e.stopPropagation()
            });
            // 阴影关闭拼单弹窗
            oPoupCloseBtn.on('click',function (e) {
                oShadow.hide();
                oSpellListPopup.hide();
                e.stopPropagation()
            });
        },

        // 倒计时
        CutDataTime : function (data) {
            var Atimes = [];
            var _this = this;
            for(var i = 0;i < data.length;i++){
                var creatDate = new Date(data[i].createDate);                    // 设置创建时间
                var creat = creatDate.getTime();
                var endDate = new Date(data[i].tgEndDate);                        // 设置截止时间
                var end = endDate.getTime();
                Atimes.push(creat);
                setInterval(function () {
                    Atimes.forEach(function (el,index) {
                        var nowDate = new Date();
                        var now = nowDate.getTime();
                        var startTime = el+24*3600*1000;
                        var leftTime = startTime - end;         // 时间差
                        if(leftTime > 0) {
                            _this.curentTime((end - now),index)
                        }else{
                            _this.curentTime((startTime - now),index)
                        }
                    });
                },50)
            }
        },

        // 倒计时计算
        curentTime:function (date,index) {
            var _this = this;
            if(date <= 0){
                $('.js_spellListArea').find('.js_timeDel').eq(index).html('00:00:00.');
                $('.js_spellListArea').find('.js_msTime').eq(index).html('0');
                oSpellPopupList.find('.js_timeDel').eq(index).html('00:00:00.');
                oSpellPopupList.find('.js_msTime').eq(index).html('0');
            }else{
                var hh, mm, ss, ms;
                hh = Math.floor(date / 1000 / 60 / 60 % 24);
                mm = Math.floor(date / 1000 / 60 % 60);
                ss = Math.floor(date / 1000 % 60);
                var mstring = date % 1000+'';
                ms = Number(mstring.substring(0,2));

                ss = ss < 10 ? ('0' + ss) : ss;
                mm = mm < 10 ? ('0' + mm) : mm;
                hh = hh < 10 ? ('0' + hh) : hh;
                ms = ms < 10 ? ('0' + ms) : ms;
                $('.js_spellListArea').find('.js_timeDel').eq(index).html(hh+':'+mm+':'+ss+'.');
                $('.js_spellListArea').find('.js_msTime').eq(index).html(ms);
                oSpellPopupList.find('.js_timeDel').eq(index).html(hh+':'+mm+':'+ss+'.');
                oSpellPopupList.find('.js_msTime').eq(index).html(ms);
            }
        }
    };
    spellList.spellListData();
    spellList.spellListEvent();
});